﻿#include "httprequest.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QNetworkReply>
#include <QDebug>
#include <QVector>
#include <QDateTime>
#include <QApplication>
#include <QFile>
#include <QFileInfo>
#include <QTextCodec>
#include "common.h"
#include "systeminfomation.h"

HttpRequest::HttpRequest()
{
    m_networkAccessManager = new QNetworkAccessManager();
    connect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), \
        this, SLOT(dealNetworkFinisheded(QNetworkReply*)));
}

HttpRequest::~HttpRequest()
{
    if(m_networkAccessManager) {
        delete m_networkAccessManager;
        m_networkAccessManager = nullptr;
    }
}

void HttpRequest::setUrls(RequestType type, const QString url)
{
    m_type = type;
    m_request.setUrl(url);
}

void HttpRequest::fillDatas(const RequestType& type, const QString& url)
{
    m_mapUrl.insert(type, url);
}

void HttpRequest::getStockInfo(const QString& code)
{
    auto url = m_mapUrl.value(kDongFangCaiFuRequest) + "q=" + code;
    setUrls(kDongFangCaiFuRequest, url);
    m_networkAccessManager->get(m_request);
}

void HttpRequest::dealNetworkFinisheded(QNetworkReply *reply)
{       
    QByteArray recvData = reply->readAll();
    qInfo() << "recvData: " << recvData;
    reply->deleteLater();
    reply = nullptr;
    switch (type()) {
    case kDongFangCaiFuRequest: {
        auto parseString = QString::fromLocal8Bit(recvData);
        auto temp = parseString.mid(parseString.indexOf("="));
        // "1~ST\xB6\xAB\xB1\xB1\xB8\xDF~600003~3.87~3.87~0.00"
        QStringList list = temp.split("~");
        if(list.size() > 5) {
            qDebug() << list.value(0);
            qDebug() << list.value(1);
            qDebug() << list.value(2);
            qDebug() << list.value(3);
            qDebug() << list.value(4);
            emit signalStockInfomation(list.value(1), list.value(3));
        }
        qDebug() << parseString;
    }
        break;
    default:
        break;
    }
}
